﻿using System;
using System.Windows;
using ParaEditor.Desktop.Service.LogMgrService.Impl;

namespace ParaEditor.Desktop
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private LogMgrServiceImpl _log = new LogMgrServiceImpl();
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

#if (DEBUG)
            RunInDebugMode();
#else
            RunInReleaseMode();
#endif
            this.ShutdownMode = ShutdownMode.OnMainWindowClose;
        }

        private static void RunInDebugMode()
        {
            AFCBootstrapper bootstrapper = new AFCBootstrapper();
            bootstrapper.Run();
        }

        private static void RunInReleaseMode()
        {
            AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException;
            try
            {
                AFCBootstrapper bootstrapper = new AFCBootstrapper();
                bootstrapper.Run();
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        private static void AppDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                Microsoft.Windows.Controls.MessageBox.Show("程序内部错误，请重新进行操作！");
                HandleException(e.ExceptionObject as Exception);
            }
            catch (Exception ex)
            {
                Microsoft.Windows.Controls.MessageBox.Show("程序内部错误，请重新进行操作！");
            }
            
        }

        private static void HandleException(Exception ex)
        {
            if (ex == null)
                return;

            // ExceptionPolicy.HandleException(ex, "Default Policy");
            //MessageBox.Show(AFC.LC.Monitor.Properties.Resources.UnhandledException);
            Environment.Exit(1);
        }

        private void Application_Exit(object sender, ExitEventArgs e)
        {
            try
            {
                _log.writeLog("一般操作日志", "0", "", "操作员" + ApplictionDatacontext.opt.OPERATOR_ID + "登出");
            }
            catch (Exception ex)
            {
            }
        }
    }
}
